package web_socket

import (
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
)

var (
	upGrader = websocket.Upgrader{
		//允许跨域访问
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

var connects = make([]*websocket.Conn, 0)

const (
	FuncHint    = "hint"     // 消息提示
	FuncOpenBox = "open_box" // 开仓
)

type WebSocketMsg struct {
	Func string
	Data interface{}
}

func Init() {
	http.HandleFunc("/ws", wsHandler)
	//服务端启动
	go func() {
		e := http.ListenAndServe(":8080", nil)
		if e != nil {
			fmt.Println(e)
		}
	}()
}

func Write(text string) {
	for _, v := range connects {
		if v != nil {
			_ = v.WriteMessage(websocket.TextMessage, []byte(text))
		}
	}
}

func Hint(content string, wait int) {
	Write(fmt.Sprintf("hint,%s,%d", content, wait))
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
	var (
		conn *websocket.Conn
		err  error
		data []byte
	)
	if conn, err = upGrader.Upgrade(w, r, nil); err != nil {
		fmt.Println(err)
		//报错了，直接返回底层的websocket链接就会终断掉
		return
	}
	fmt.Println("新连接。。。。。。")
	connects = append(connects, conn)
	//得到了websocket.Conn长连接的对象，实现数据的收发
	for {
		if _, data, err = conn.ReadMessage(); err != nil {
			_ = conn.Close()
			fmt.Println("连接关闭")
			break
		} else {
			fmt.Println(string(data))
		}
	}
}
